<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2>雷恒_图书借阅管理系统登录</h2>
      </div>
      <el-form ref="form" :model="form" :rules="rules" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" prefix-icon="el-icon-lock" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleLogin" :loading="loading">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      loading: false
    }
  },
  methods: {
    handleLogin() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          axios
            .post('http://localhost:8181/user/login', {
              username: this.form.username,
              password: this.form.password
            })
            .then(resp => {
              if (resp.data && resp.data.id) {
                // 存储用户信息
                localStorage.setItem('userId', resp.data.id.toString())
                localStorage.setItem('username', resp.data.username || this.form.username)
                localStorage.setItem('userRole', resp.data.role || (this.form.username === 'admin' ? 'admin' : 'user'))

                // 根据角色跳转
                const isAdmin = resp.data.role === 'admin' || this.form.username === 'admin'
                this.$router.push(isAdmin ? '/admin/BookManage' : '/user/home')
              } else {
                this.$message.error('登录失败: 无效的用户数据')
              }
            })
            .catch(error => {
              this.$message.error('登录失败: ' + (error.response?.data?.message || error.message))
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #409eff;
}

.login-form {
  margin-top: 20px;
}

.login-btn {
  width: 100%;
}
</style>
